package com.example.weiji_1;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import wordroid.model.TextList;
import wordroid.model.UnitList;
import wordroid.model.Massage;

import com.example.weiji_1.datebase.DataAccess;
import com.example.weiji_1.datebase.SqlHelper;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class Tabshow extends Activity {
	 private ViewPager viewPager;//椤靛崱鍐呭 
	    private ImageView imageView;// 鍔ㄧ敾鍥剧墖 
	    private TextView textView1,textView2,textView3,textView4; 
	    private TextView first_textview1,first_textview2,first_textview3,first_textview4;
	    private Spinner pickBook ;
	    private List<View> views;// Tab椤甸潰鍒楄〃   
	    private int offset = 0;// 鍔ㄧ敾鍥剧墖鍋忕Щ閲�
	    private int currIndex = 0;// 褰撳墠椤靛崱缂栧彿
	    private int bmpW;// 鍔ㄧ敾鍥剧墖瀹藉害
	    private View view1,view2,view3,view4;//鍚勪釜椤靛崱
	    
	
		@Override
		protected void onCreate(Bundle savedInstanceState) 
		{
			super.onCreate(savedInstanceState);
			requestWindowFeature(Window.FEATURE_NO_TITLE);// 鍘绘帀鏍囬鏍�
			setContentView(R.layout.main);
			 File dir = new File("data/data/com.example.weiji_1/databases"); 
		       
		        if (!dir.exists()) 
		            dir.mkdir(); 
			 if (!(new File(SqlHelper.DB_NAME)).exists()) { 
		         FileOutputStream fos;
					try {
						fos = new FileOutputStream(SqlHelper.DB_NAME);
					
		            byte[] buffer = new byte[8192]; 
		            int count = 0; 
		            InputStream is = getResources().openRawResource( 
		                    R.raw.weiji); 
		            while ((count = is.read(buffer)) > 0) { 
		                fos.write(buffer, 0, count); 
		            }

		            fos.close(); 
		            is.close(); 
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
		        }
			InitImageView();  
	        InitTextView();  
	        InitViewPager();  
	        initWidgets();
	        
		}
		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event)
		{
			if (keyCode == KeyEvent.KEYCODE_BACK )
			{
				// 鍒涘缓閫�嚭瀵硅瘽妗�
				AlertDialog isExit = new AlertDialog.Builder(this).create();
				// 璁剧疆瀵硅瘽妗嗘爣棰�
				isExit.setTitle("          閫�嚭寰満涓�偣閫�");
				// 璁剧疆瀵硅瘽妗嗘秷鎭�
				//isExit.setMessage("              纭畾瑕侀�鍑哄悧");
				// 娣诲姞閫夋嫨鎸夐挳骞舵敞鍐岀洃鍚�
				isExit.setButton("纭畾", listener);
				isExit.setButton2("鍙栨秷", listener);
				// 鏄剧ず瀵硅瘽妗�
				isExit.show();

			}
			
			return false;
			
		}
		/**鐩戝惉瀵硅瘽妗嗛噷闈㈢殑button鐐瑰嚮浜嬩欢*/
		DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int which)
			{
				switch (which)
				{
				case AlertDialog.BUTTON_POSITIVE://// "纭"鎸夐挳閫�嚭绋嬪簭
					finish();
					break;
				case AlertDialog.BUTTON_NEGATIVE://"鍙栨秷"绗簩涓寜閽彇娑堝璇濇
					break;
				default:
					break;
				}
			}
		};	
		
		 private void InitViewPager() 
		 {  
		        viewPager=(ViewPager) findViewById(R.id.vPager);  
		        views=new ArrayList<View>();  
		        LayoutInflater inflater=getLayoutInflater();  
		        view1=inflater.inflate(R.layout.tab1, null);  
		        view2=inflater.inflate(R.layout.tab2, null);  
		        view3=inflater.inflate(R.layout.tab3, null);  
		        view4=inflater.inflate(R.layout.tab4, null); 
		        views.add(view1);  
		        views.add(view2);  
		        views.add(view3);
		        views.add(view4); 
		      
		        viewPager.setAdapter(new MyViewPagerAdapter(views));  
		        viewPager.setCurrentItem(0);  //褰撳墠椤圭洰
		        viewPager.setOnPageChangeListener((OnPageChangeListener) new MyOnPageChangeListener());  
		    }  
		 /** 
	      *  鍒濆鍖栧ご鏍�
	      */  
		    private void InitTextView()
		    {  
		        textView1 = (TextView) findViewById(R.id.text1);  
		        textView2 = (TextView) findViewById(R.id.text2);  
		        textView3 = (TextView) findViewById(R.id.text3);
		        textView4 = (TextView) findViewById(R.id.text4); 
		  
		        textView1.setOnClickListener((OnClickListener) new MyOnClickListener(0));  
		        textView2.setOnClickListener(new MyOnClickListener(1));  
		        textView3.setOnClickListener(new MyOnClickListener(2)); 
		        textView4.setOnClickListener(new MyOnClickListener(3));
		    }  
		  
		    /** 
		     2      * 鍒濆鍖栧姩鐢伙紝杩欎釜灏辨槸椤靛崱婊戝姩鏃讹紝涓嬮潰鐨勬í绾夸篃婊戝姩鐨勬晥鏋滐紝鍦ㄨ繖閲岄渶瑕佽绠椾竴浜涙暟鎹�
		     3 */  
		  
		    private void InitImageView()
		    {  
		        imageView= (ImageView) findViewById(R.id.cursor);  
		        bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.background).getWidth();// 锟斤拷取图片锟斤拷锟� 
		        DisplayMetrics dm = new DisplayMetrics();  
		        getWindowManager().getDefaultDisplay().getMetrics(dm);  
		        int screenW = dm.widthPixels;// 鑾峰彇鍒嗚鲸鐜囧搴�
		        offset = (screenW / 4 - bmpW) / 2;// 璁＄畻鍋忕Щ閲�
		        Matrix matrix = new Matrix();  
		        matrix.postTranslate(offset, 0);  
		        imageView.setImageMatrix(matrix);// 璁剧疆鍔ㄧ敾鍒濆浣嶇疆 
		    }
		    
		    private void initWidgets() {
				// TODO Auto-generated method stub
				first_textview1=(TextView) this.view1.findViewById(R.id.textView3);
				first_textview2=(TextView) this.view1.findViewById(R.id.textView6);
				//first_textview1.setText("10"+"  / " + "100");
				//first_textview2.setText("10"+"  / " + "100");
				pickBook=(Spinner) this.view1.findViewById(R.id.pickBook);
				/*deleteBu.setOnClickListener(this);
				this.info=(TextView) myView.findViewById(R.id.bookinfo);
				this.learnBu=(Button) myView.findViewById(R.id.learn);
				learnBu.setOnClickListener(this);
				this.pickBook=(Spinner) myView.findViewById(R.id.pickBook);
				this.resetBu=(ImageButton) myView.findViewById(R.id.reset);
				resetBu.setOnClickListener(this);
				this.reviewBu=(Button) myView.findViewById(R.id.review);
				reviewBu.setOnClickListener(this);
				this.testBu=(Button) myView.findViewById(R.id.test);
				testBu.setOnClickListener(this);
				this.attentionBu=(Button) myView.findViewById(R.id.attention);
				attentionBu.setOnClickListener(this);
				this.learn_progress= (ProgressBar) myView.findViewById(R.id.learn_progress);
				this.review_progress= (ProgressBar) myView.findViewById(R.id.review_progress);
				this.review_text=(TextView) myView.findViewById(R.id.review_text);
				this.learn_text=(TextView) myView.findViewById(R.id.learn_text);
				DisplayMetrics dm = new DisplayMetrics(); 
				   dm = getApplicationContext().getResources().getDisplayMetrics(); 
				   int screenWidth = dm.widthPixels; 
				   int padding = (screenWidth-200);
				   this.learnBu.setPadding(padding/5, 0, padding/10, 0);
				   this.resetBu.setPadding(padding/10, 0, padding/10, 0);
				   this.testBu.setPadding(padding/10, 0, padding/10, 0);
				   this.attentionBu.setPadding(padding/10, 0, padding/5, 0);*/
				initSpinner();
			}
		    
		    
		    private void initSpinner() {
				DataAccess data = new DataAccess(this);
				final ArrayList<UnitList> unitList = data.QueryUnit(null, null);
				final ArrayList<TextList> textList = data.QueryText(null, null);
				//Log.i("size", String.valueOf(bookList.size()));
				String[] units = new String[unitList.size()+1];
				int i=0;
				for (;i<unitList.size();i++){
					units[i]=unitList.get(i).getunitID();
				}
				units[i]="瀵煎叆鏂拌瘝搴�";
				
				//pickBook.setPrompt("璇烽�鎷╁唴瀹癸細"); 
				//first_textview1.setText(textList.get(i).getlearned()+"  / " + textList.get(i).getallnum());
				//first_textview2.setText("10"+"  / " + "100");
				ArrayAdapter< CharSequence > adapter = new ArrayAdapter< CharSequence >(this, android.R.layout.simple_spinner_dropdown_item, units);

				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				pickBook.setAdapter(adapter);
				pickBook.setOnItemSelectedListener(new OnItemSelectedListener(){
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						if (arg2<unitList.size()){
							DataAccess.bookID=unitList.get(arg2).getunitID();
							first_textview1.setText(unitList.get(arg2).getLearned()+"  / " + unitList.get(arg2).getallnum());
							first_textview2.setText(textList.get(arg2).getlearned()+"  / " + textList.get(arg2).getallnum());
							//info.setText("\n璇嶅簱鍚嶇О:\n    "+bookList.get(arg2).getName()+"\n鎬昏瘝姹囬噺:\n    "+bookList.get(arg2).getNumOfWord()+"\n锟斤拷锟斤拷时锟戒：\n    "+bookList.get(arg2).getGenerateTime());
							//deleteBu.setEnabled(true);
							//learnBu.setEnabled(true);
							//resetBu.setEnabled(true);
							//reviewBu.setEnabled(true);
							//testBu.setEnabled(true);
							//DataAccess data2 = new DataAccess(Tabshow.this);
							//ArrayList<UnitList> lists = data2.QueryList("BOOKID ='"+DataAccess.bookID+"'", null);
							//learn_progress.setMax(lists.size());
							//review_progress.setMax(lists.size());
							//learn_progress.setProgress(0);
							//review_progress.setProgress(0);
							//.setSecondaryProgress(0);
							//int learned=0,reviewed=0;
							//for (int k=0;k<lists.size();k++){
							//	if (lists.get(k).getLearned().equals("1")){
								//	learn_progress.incrementProgressBy(1);
								//	learned++;
								//}
								
								/*if (Integer.parseInt(lists.get(k).getReview_times())>=5){
									review_progress.incrementProgressBy(1);
									reviewed++;
								}
								
								if (Integer.parseInt(lists.get(k).getReview_times())>0)
								review_progress.incrementSecondaryProgressBy(1);
								review_text.setText("宸插涔�+reviewed+"/"+lists.size());
								learn_text.setText("宸插涔�+learned+"/"+lists.size());
							}
						}
						else if(arg2==bookList.size()){
							Intent intent = new Intent();
							intent.setClass(Main.this, ImportBook.class);
							startActivity(intent);
						}
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub
						
					}
					
				});
				if (bookList.size()==0) {
					pickBook.setSelection(1);
					info.setText("璇峰厛浠庝笂鏂归�鎷╀竴涓瘝搴擄紒");
					this.deleteBu.setEnabled(false);
					this.learnBu.setEnabled(false);
					this.resetBu.setEnabled(false);
					this.reviewBu.setEnabled(false);
					this.testBu.setEnabled(false);
					this.learn_progress.setProgress(0);
					this.review_progress.setProgress(0);
					return;
				}
				int j=0;
				Log.i("BookID", DataAccess.bookID);
				for (;j<bookList.size();j++){
					if (DataAccess.bookID.equals(bookList.get(j).getID())){
						pickBook.setSelection(j);	
						break;
					}*/
						
				}
			}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub
						
					}
				});
		    }
			
		    
		    /******************* 澶存爣鐐瑰嚮鐩戝惉 3 *************************/ 
		    
		    private class MyOnClickListener implements OnClickListener
		    {  
		        private int index=0;  
		        public MyOnClickListener(int i)
		        {  
		            index=i;  
		        }  
		        public void onClick(View v) 
		        {  
		            viewPager.setCurrentItem(index);              
		        }  
		          
		    }  
		      
		    public class MyViewPagerAdapter extends PagerAdapter
		    {  
		        private List<View> mListViews;  
		          
		        public MyViewPagerAdapter(List<View> mListViews) 
		        {  
		            this.mListViews = mListViews;  
		        }  
		  
		        @Override  
		        public void destroyItem(ViewGroup container, int position, Object object)   
		        {     
		            container.removeView(mListViews.get(position));  
		        }  
		  
		  
		        @Override  
		        public Object instantiateItem(View arg0, int position) {            
		             ((ViewPager)arg0).addView(mListViews.get(position), 0);
		             if(position == 0)
		             {
				    		Button bt1 = (Button)arg0.findViewById(R.id.button1);
				    		Button bt2 = (Button)arg0.findViewById(R.id.button2);
				    		bt1.setOnClickListener(new View.OnClickListener() 
				    		{
				    			
				    			@Override
				    			public void onClick(View arg0) 
				    			{
				    				Toast.makeText(getApplicationContext(), "宸叉竻闄ゅ涔犺褰�",0).show();;
				    				
				    			}
				    		});
				    		bt2.setOnClickListener(new View.OnClickListener() 
				    		{
				    			
				    			@Override
				    			public void onClick(View arg0) 
				    			{
				    				// TODO Auto-generated method stub
				    				Intent intent = new Intent();
				    				intent.setClass(Tabshow.this, record.class);
				    				startActivity(intent);
				    				//finish();
				    				
				    			}
				    		});
		             }
		             if(position == 1)
		             {
		            	 	buttonListener1 btnliListener1 = new buttonListener1();
					        buttonListener1 btnliListener2 = new buttonListener1();
					        buttonListener1 btnliListener3 = new buttonListener1();
					        buttonListener1 btnliListener4 = new buttonListener1();
					        buttonListener1 btnliListener5 = new buttonListener1();
					        
							Button bt1 = (Button)arg0.findViewById(R.id.imageButton1);
							Button bt2 = (Button)arg0.findViewById(R.id.ImageButton01);
							Button bt3 = (Button)arg0.findViewById(R.id.ImageButton03);
							Button bt4 = (Button)arg0.findViewById(R.id.ImageButton04);
							
							bt1.setOnClickListener(btnliListener1);
						    bt2.setOnClickListener(btnliListener2);
						    bt3.setOnClickListener(btnliListener3);
						    bt4.setOnClickListener(btnliListener4);
						    
		             }
		             if(position == 2)
		             {
		            	 	buttonListener2 btnliListener1 = new buttonListener2();
					        buttonListener2 btnliListener2 = new buttonListener2();
					        buttonListener2 btnliListener3 = new buttonListener2();
					        buttonListener2 btnliListener4 = new buttonListener2();
					        buttonListener2 btnliListener5 = new buttonListener2();
					        
							Button bt1 = (Button)arg0.findViewById(R.id.imageButton1);
							Button bt2 = (Button)arg0.findViewById(R.id.ImageButton01);
							Button bt3 = (Button)arg0.findViewById(R.id.ImageButton03);
							Button bt4 = (Button)arg0.findViewById(R.id.ImageButton04);
							
							bt1.setOnClickListener(btnliListener1);
						    bt2.setOnClickListener(btnliListener2);
						    bt3.setOnClickListener(btnliListener3);
						    bt4.setOnClickListener(btnliListener4);
		             }

		             return mListViews.get(position);  
		        }  
		  
		        @Override  
		        public int getCount() 
		        {           
		            return  mListViews.size();  
		        }  
		          
		        @Override  
		        public boolean isViewFromObject(View arg0, Object arg1) 
		        {             
		            return arg0==arg1;  
		        }  
		    }  
		  
		    public class MyOnPageChangeListener implements OnPageChangeListener
		    {  
		  
		        int one = offset * 2 + bmpW;//椤靛崱1 -> 椤靛崱2 鍋忕Щ閲�
		        int two = one * 2;//椤靛崱1 -> 椤靛崱3 鍋忕Щ閲�
		        public void onPageScrollStateChanged(int arg0) 
		        {  
		              
		              
		        }  
		  
		        public void onPageScrolled(int arg0, float arg1, int arg2) 
		        {  
		              
		              
		        }  
		  
		        public void onPageSelected(int arg0) 
		        {  
		             
		            Animation animation = new TranslateAnimation(one*currIndex, one*arg0, 0, 0);//锟斤拷然锟斤拷锟斤拷冉霞锟洁，只锟斤拷一锟叫达拷锟诫。  
		            currIndex = arg0;  
		            animation.setFillAfter(true);// True:鍥剧墖鍋滃湪鍔ㄧ敾缁撴潫浣嶇疆
		            animation.setDuration(300);  
		            imageView.startAnimation(animation);  
		            //Toast.makeText(Tabshow.this, "鎮ㄩ�鎷╀簡"+ viewPager.getCurrentItem()+"椤靛崱", Toast.LENGTH_SHORT).show();  
		        }
		   	 }

		       
		       
		     class buttonListener1 implements OnClickListener {
							@Override
					        public void onClick(View v) {
					            // TODO Auto-generated method stub
					            switch(v.getId()){
					            case R.id.imageButton1:
					            	//Toast.makeText(getApplicationContext(), "1", 0).show();
					            	Intent intent = new Intent();
									intent.setClass(Tabshow.this, Part1.class);
									startActivity(intent);
									//finish();
					                break;
					            case R.id.ImageButton01:
					            	//Toast.makeText(getApplicationContext(), "2", 0).show();
					            	Intent intent1 = new Intent();
									intent1.setClass(Tabshow.this, Part2.class);
									startActivity(intent1);
									//finish();
					                break;
					            case R.id.ImageButton04:
					            	//Toast.makeText(getApplicationContext(), "3", 0).show();
					            	Intent intent2 = new Intent();
									intent2.setClass(Tabshow.this, Part3.class);
									startActivity(intent2);
									//finish();
					                break;
					            case R.id.ImageButton03:
					            	//Toast.makeText(getApplicationContext(), "4", 0).show();
					            	Intent intent3 = new Intent();
									intent3.setClass(Tabshow.this, Part4.class);
									startActivity(intent3);
									//finish();
					                break;

					            	}    
					            }
							}
				        

	         class buttonListener2 implements OnClickListener {
				@Override
		        public void onClick(View v) {
		            // TODO Auto-generated method stub
		            switch(v.getId()){
		            case R.id.imageButton1:
		            	//Toast.makeText(getApplicationContext(), "1", 0).show();
		            	Intent intent = new Intent();
						intent.setClass(Tabshow.this, Text1.class);
						startActivity(intent);
						//finish();
		                break;
		            case R.id.ImageButton01:
		            	//Toast.makeText(getApplicationContext(), "2", 0).show();
		            	Intent intent1 = new Intent();
						intent1.setClass(Tabshow.this, Text2.class);
						startActivity(intent1);
						//finish();
		                break;
		            case R.id.ImageButton04:
		            	//Toast.makeText(getApplicationContext(), "3", 0).show();
		            	Intent intent2 = new Intent();
						intent2.setClass(Tabshow.this, Text3.class);
						startActivity(intent2);
						//finish();
		                break;
		            case R.id.ImageButton03:
		            	//Toast.makeText(getApplicationContext(), "4", 0).show();
		            	Intent intent3 = new Intent();
						intent3.setClass(Tabshow.this, Text4.class);
						startActivity(intent3);
						//finish();
		                break;

		            }    
		            
		            
		        }
				
	        
	        
	        }
}
		  
		
